const Mongoose = require("mongoose");

const { resolve } = require("path");

const { readdirSync, existsSync } = require("fs");

exports.initMongoose = function (options) {
	// 将所有的骨架Schema定义加载,然后绑定到this作用域上

	const scope = this;

	Mongoose.Promise = global.Promise;

	let opts = {
		[`user`]: options.user,
		[`pass`]: options.pass,
		[`autoReconnect`]: options.autoReconnect
	};

	Mongoose.connect(
		`mongodb://${options.host}:${options.port}/${options.database}`,
		opts
	);

	Mongoose.connection.on(
		"error",
		options.errorFn || console.error.bind(console, "connection error:")
	);

	// 创建连接
	if (!options.schemaDefineRoot) {
		return new Error("hopeMongoose缺少`schemaDefineRoot`配置");
	}

	let modelRootPath = resolve(
		options.schemaDefineRoot,
		options.version || "v1"
	);

	if (!existsSync(modelRootPath)) {
		return new Error("hopeMongoose的`schemaDefineRoot`配置路径不存在");
	}

	// 遍历模型定义目录,获取所有模型定义
	readdirSync(modelRootPath).forEach(file => {
		if (!file) return;

		let modelName = file.substring(0, file.indexOf("."));

		let documentConfigFn = require(resolve(modelRootPath, file));

		let [documentConfig, documentOptions] = documentConfigFn(
			Mongoose.Schema.Types
		);

		let schema = new Mongoose.Schema(documentConfig, documentOptions || {});

		let model = Mongoose.model(modelName, schema);

		Object.defineProperty(scope, modelName, {
			writable: false,
			configurable: false,
			enumerable: false,
			value: model
		});
	});
};

exports.Mongoose = Mongoose;
